<template>
  <div class="charge-report-wrap">
    <div :class="{'mobile-table mobile-pt mobile-min-height':showMobilePage}" class="table-list min-fill-page">
      <DataDisplay :data-list="statisticsList" class="mb16 mobile-data"/>
      <div v-if="!showMobilePage" style="position:relative;margin-bottom:16px;">
        <FilterInput v-model="filterInput" :filter-list="filterList" is-show-config show-search-btn class="FilterTool" @handelClick="queryClick" @queryEmpty="queryEmpty" @filterTagStatus="filterTagStatus" />
        <div class="table-top-opeator-bar">
          <btnGroup
            v-if="hasRouteAuth('crm:chargeReport:export')"
            ref="btnGroupRef"
            :list="[{label:'导出', exportApi:'/admin/chargeReport/export', exportName:'核销记录', beforeExport: beforeExport, type: 'export', auth: hasRouteAuth('crm:chargeReport:export')}]"
          />
        </div>
      </div>
      <div v-loading="listLoading" style="min-height: 300px;">
        <u-table
          v-if="list.items.length > 0"
          ref="chargeRecordTable"
          :data="list.items"
          :height="setTableHeight"
          :row-class-name="tableRowClassName"
          :row-height="rowHeight()"
          :border="true"
          beautify-table
          header-drag-style
          row-key="id"
          use-virtual
          class="fb-table"
          element-loading-text="加载中..."
          empty-text="暂无数据"
          header-cell-class-name="order-data-header-cell"
          fit
          hightlight-current-row
          @select="selectTable"
          @select-all="selectTable"
          @sort-change="sortMethod">
          <u-table-column
            :reserve-selection="true"
            align="center"
            fixed="left"
            type="selection"
            width="50" />
          <u-table-column align="left" label="订单编号" min-width="190">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.orderId" is-can-click @handelClick="openOrderDetail(scope.row)" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="销售" min-width="120">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.sale" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="订单封账月份" min-width="130" prop="sealMonth" sortable="custom">
            <template slot-scope="scope">
              {{ scope.row.sealMonth || '--' }}
            </template>
          </u-table-column>
          <u-table-column align="left" label="下单日期" min-width="110" prop="placeOrderStart" sortable="custom">
            <template slot-scope="scope">
              {{ scope.row.placeOrderDate | format('YYYY/MM/DD') }}
            </template>
          </u-table-column>
          <u-table-column align="left" label="客户名称" min-width="140">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.clientName" />
            </template>
          </u-table-column>
          <u-table-column align="right" label="含税金额(元)" min-width="130" prop="taxAmount" sortable="custom">
            <template slot-scope="scope">
              <PriceColumn :real-val="scope.row.taxAmount" :price="scope.row.taxAmount / 100" />
            </template>
          </u-table-column>
          <u-table-column align="right" label="核销金额(元)" min-width="130" prop="enterAccountAmount" sortable="custom">
            <template slot-scope="scope">
              <div class="flex" style="justify-content: flex-end">
                <span v-if="scope.row.isLoseEfficacy === 1" style="color: #E54C4C;">(已重置)</span>
                <PriceColumn :real-val="scope.row.enterAccountAmount" :price="scope.row.enterAccountAmount / 100" />
              </div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="付款人名称" min-width="110">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.payer" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="到账日期" width="110" prop="intoAccountDate" sortable="custom">
            <template slot-scope="scope">
              {{ scope.row.intoAccountDate | format('YYYY/MM/DD') }}
            </template>
          </u-table-column>
          <u-table-column align="left" label="核销日期" width="110" prop="chargeDate" sortable="custom">
            <template slot-scope="scope">
              {{ scope.row.chargeDate | format('YYYY/MM/DD') }}
            </template>
          </u-table-column>
          <u-table-column align="left" label="流水单号" min-width="170">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.flowId" is-can-click @handelClick="openFlowDetail(scope.row)" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="核销编号" min-width="160">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.verificationId" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="付款方式" min-width="110">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.payMethodName" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="付款账号" min-width="150">
            <template slot-scope="scope">
              <SecretText
                :log-text="`财务核销记录${scope.row.flowId}的付款账号`"
                :origin-text="scope.row.payAccount" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="交易单号" min-width="150">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.trasactionId" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="流水创建人员" min-width="120">
            <template slot-scope="scope">
              <CheckUserInfo v-if="scope.row.flowCreater" :label="scope.row.flowCreater" :user-id="scope.row.flowCreaterId" />
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="核销人员" min-width="100">
            <template slot-scope="scope">
              <CheckUserInfo v-if="scope.row.charger" :label="scope.row.charger" :user-id="scope.row.charger==='自动核销'?'':scope.row.chargerId" />
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="封账状态" min-width="100">
            <template slot-scope="scope">
              <StatusText :color="['#406EFF', '#31CC9C', '#FD8546'][scope.row.sealStatus]" :text="scope.row.sealStatus | setSealBillType" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="类型" min-width="100">
            <template slot-scope="scope">
              {{ scope.row.flowType | flowType }}
            </template>
          </u-table-column>
          <u-table-column align="left" label="封账月份" min-width="100" prop="sealingMonth" sortable="custom">
            <template slot-scope="scope">
              {{ scope.row.sealingMonth || '--' }}
            </template>
          </u-table-column>
          <u-table-column fixed="right" align="left" label="操作">
            <template slot-scope="scope">
              <div
                v-if="scope.row.sealStatus === 0 && (scope.row.category === 0 || (scope.row.category === 1 && scope.row.projectStatus <= 1) || scope.row.category === 2)"
                class="button-text"
                @click="toRepeal(scope)">撤销核销</div>
              <div v-else>--</div>
            </template>
          </u-table-column>
        </u-table>
        <empty-placeholder v-else-if="!list.isInit" style="margin-bottom: 24px" />
      </div>
      <el-row v-if="showMobilePage" type="flex" justify="left">
        <el-pagination
          v-show="list.total > 0"
          :current-page.sync="list.page"
          :page-size="list.perPage"
          :total="list.total"
          :small="true"
          :page-sizes="[20, 50, 100, 250, 500]"
          :layout="pageLayout"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-row>
      <fixed-pagination v-show="list.total > 0 && !showMobilePage || showMobilePage">
        <template v-if="showMobilePage">
          <FilterInput v-model="filterInput" :filter-list="filterList" is-show-config show-mobile-icon show-search-btn class="FilterTool" @handelClick="queryClick" @queryEmpty="queryEmpty" @filterTagStatus="filterTagStatus" />
          <MoreOpeator
            v-if="hasRouteAuth('crm:chargeReport:export')"
            ref="moreOpeatorRef"
            :list="[
              {label:'导出', exportApi:'/admin/chargeReport/export', exportName:'核销记录', isBeforeExport: true, beforeExport: beforeExport, type: 'export', auth: hasRouteAuth('crm:chargeReport:export'), refName: 'chargeExportRef' }
            ]"
            show-mobile-icon
          />
        </template>
        <template v-else>
          <el-button
            class="delete-button"
            size="small"
            @click="toBatchRepeal">批量撤销核销</el-button>
          <div style="flex:1;display: flex;align-items: center;">
            <div v-if="selectData.length" class="select-box-style">
              <span class="select-data-num" style="margin-right: 0;">已选 <span>{{ selectData.length }}</span> 条</span>
              <el-button type="text" @click="clearSelect"><span class="el-icon-close"/></el-button>
            </div>
          </div>
          <el-pagination
            :current-page="list.page"
            :page-size="list.perPage"
            :total="list.total"
            :page-sizes="[20, 50, 100, 250, 500]"
            layout="total, prev, pager, next, sizes, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </template>
      </fixed-pagination>
    </div>
  </div>
</template>
<script>
// api
import { getChargeReports, cancelWriteOff, batchCancelWriteOff, getchargeStatistics } from '@/api/finance';
import { getPayOption } from '@/api/select';
// filters
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import { format } from '@/filters/date';
import { setSealBillType } from '@/filters/status';
import { hasRouteAuth } from '@/utils/permission';
import { showModal } from '@/utils/message';
import ElMessage from '@/utils/message';
import btnGroup from '@/components/Common/baseComponent/btnGroup';
import DataDisplay from '@/components/Common/baseComponent/dataDisplay';
import MoreOpeator from '@/components/Common/baseComponent/moreOpeator';
// mixins
import paramsDateFormat from '@/mixins/paramsDateFormat';
import TableAdaptive from '@/mixins/tableAdaptive';
import { paramsAryToStr } from '@/utils/paramsFormat';
import mobileTable from '@/mixins/mobileTable';
import icon_4 from '@/assets/dataDisplay/icon_4.png';
import icon_35 from '@/assets/dataDisplay/icon_35.png';
import icon_6 from '@/assets/dataDisplay/icon_6.png';
import '@/styles/extend.scss';
import axios from 'axios';

export default {
  name: 'ChargeReport',
  filters: {
    format,
    setSealBillType,
    flowType(val) {
      // 流水类型。0:普通 1:对抵
      if (![0, 1].includes(val)) return '--';
      return {
        0: '普通',
        1: '对抵'
      }[val];
    }
  },
  components: {
    EmptyPlaceholder,
    btnGroup,
    DataDisplay,
    MoreOpeator
  },
  mixins: [paramsDateFormat, TableAdaptive, mobileTable],
  data() {
    return {
      sortType: '',
      sortName: '',
      perPage: 20,
      list: {
        items: [],
        page: 1,
        perPage: 20,
        total: 0,
        isInit: true,
        totalAmount: '',
        amount: {}
      },
      filterInput: {},
      listLoading: false,
      filterList: [
        { keyword: 'verificationId', name: '核销编号', type: 'input', labelWidth: '100px' },
        { keyword: 'orderId', name: '订单编号', type: 'input' },
        { keyword: 'payer', name: '付款人名称', type: 'input', labelWidth: '100px' },
        { keyword: 'clientName', name: '客户名称', type: 'input' },
        { keyword: 'payAccount', name: '付款账号', type: 'input', labelWidth: '100px' },
        { keyword: 'trasactionId', name: '交易单号', type: 'input' },
        { keyword: 'flowId', name: '流水单号', type: 'input', labelWidth: '100px' },
        { keyword: 'flowCreater', name: '流水创建人', type: 'input' },
        { keyword: 'sale', name: '销售', type: 'inputSearch', tagName: 'sale', labelWidth: '100px' },
        { keyword: 'payMethod', name: '付款方式', type: 'select', options: [{ value: -1, label: '全部' }] },
        {
          keyword: 'sealStatus', name: '封账状态', type: 'select',
          options: [{ value: -1, label: '全部' }, { value: 0, label: '待封账' }, { value: 2, label: '封账中' }, { value: 1, label: '已封账' }]
        },
        { keyword: 'flowType', name: '类型', type: 'select', labelWidth: '40px', options: [{ value: 0, label: '普通' }, { value: 1, label: '对抵' }] },
        { keyword: 'intoAccountTime', name: '到账日期', type: 'rangeDate', timeType: 'daterange', format: 'yyyy/MM/dd' },
        { keyword: 'chargeTime', name: '核销日期', type: 'rangeDate', timeType: 'daterange', format: 'yyyy/MM/dd', labelWidth: '100px' },
        { keyword: 'placeOrderTime', name: '下单日期', type: 'rangeDate', timeType: 'daterange', format: 'yyyy/MM/dd' },
        { keyword: 'sealingMonth', name: '封账月份', timeType: 'monthrange', type: 'rangeDate', format: 'yyyy/MM', labelWidth: '100px' },
        { keyword: 'sealMonth', name: '订单封账月份', timeType: 'monthrange', type: 'rangeDate', format: 'yyyy/MM' },
        {
          keyword: 'charger',
          name: '核销人员',
          type: 'loadMoreSelect',
          valueName: 'id',
          multiple: true,
          labelName: 'userName',
          placeholder: '核销人员',
          searchkeyword: 'userName',
          apiUrl: '/admin/user/list' }
      ],
      dateDataAttrName: [
        {
          attr: 'intoAccountTime',
          start: 'intoAccountStart',
          end: 'intoAccountEnd',
          endType: 1
        },
        {
          attr: 'chargeTime',
          start: 'chargeStart',
          end: 'chargeEnd',
          endType: 1
        },
        {
          attr: 'placeOrderTime',
          start: 'placeOrderStart',
          end: 'placeOrderEnd',
          endType: 1
        },
        {
          attr: 'sealingMonth',
          start: 'sealingMonthStart',
          end: 'sealingMonthEnd',
          endType: 1
        },
        {
          attr: 'sealMonth',
          start: 'sealMonthStart',
          end: 'sealMonthEnd',
          endType: 1
        }
      ],
      isUmyTable: true,
      ids: '',
      selectData: [],
      statisticsList: [],
      cancelToken: null
    };
  },
  computed: {
    arrayKeyArr() {
      return ['charger'];
    },
    tableOutsideHeight() {
      return this.showMobilePage ? 205 : 246;
    }
  },
  created() {
    this.fetchData(true);
    this.getPaySelect();
  },
  methods: {
    hasRouteAuth,
    async getPaySelect() {
      try {
        const result = await getPayOption();
        if (result.code === 200) {
          const formatOption = result.data.map(item => {
            return {
              label: item.name,
              value: item.id
            };
          });
          const options = {
            keyword: 'payMethod', name: '付款方式', type: 'select',
            options: [{ value: -1, label: '全部' }, ...formatOption]
          };
          this.$set(this.filterList, this.filterList.findIndex(i => i.keyword === 'payMethod'), options);
        }
      } catch (error) {
        console.log(error);
      }
    },
    beforeExport() {
      const params = this.formatParams();
      params.ids = this.ids;
      if (this.$refs.btnGroupRef) this.$refs.btnGroupRef.btnExport(params);
      if (this.$refs.moreOpeatorRef) {
        this.$refs.moreOpeatorRef.btnExport(params, 'chargeExportRef');
      }
    },
    sortMethod(a) {
      if (!a.order) {
        this.sortName = '';
        this.sortType = '';
      } else {
        this.sortName = a.prop;
        this.sortType = a.order === 'ascending' ? 1 : -1;
      }
      this.fetchData();
    },
    formatParams() {
      const params = JSON.parse(JSON.stringify(this.filterInput));
      this.paramsDateFormat(this.dateDataAttrName, params);
      paramsAryToStr(this.arrayKeyArr, params);
      return params;
    },
    queryClick() {
      this.fetchData(true);
    },
    fetchData(reset = false) {
      if (reset) this.page = 1;
      const params = this.formatParams();
      params.sortName = this.sortName;
      params.sortType = this.sortType;
      this.listLoading = true;
      if (this.cancelToken) this.cancelToken.cancel('cancel');
      const source = axios.CancelToken.source();
      this.cancelToken = source;
      this.getStatisticsData(params, source.token);
      getChargeReports(this.page, this.perPage, params, source.token).then(({ data }) => {
        this.list = data;
        this.list.isInit = false;
        this.listLoading = false;
      }, result => {
        this.listLoading = false;
      }).catch(e => {
        console.log(e);
      });
    },
    queryEmpty() {
      this.filterInput = {};
      this.queryClick();
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.fetchData(true);
      this.$nextTick(() => {
        document.body.scrollTop = document.documentElement.scrollTop = 0;
      });
    },
    handleCurrentChange(toPage) {
      this.page = toPage;
      this.fetchData();
      this.$nextTick(() => {
        document.body.scrollTop = document.documentElement.scrollTop = 0;
      });
    },
    toRepeal(scope) {
      showModal('是否确定撤销该核销', '', {
        center: true
      }).then(() => {
        const params = {
          type: scope.row.category || 0
        };
        cancelWriteOff(scope.row.id, params).then(res => {
          this.$message.success('撤销成功');
          this.fetchData();
        }, result => {
          // this.$message.error(result.message);
        });
      }).catch(() => {
        return false;
      });
    },
    // 选择表格
    selectTable(e) {
      this.selectData = e.map(item => {
        return {
          id: item.id,
          type: item.category
        };
      });
      this.ids = e.map(item => {
        return item.id;
      }).join(',');
    },
    toBatchRepeal() {
      if (this.selectData.length === 0) {
        ElMessage.warning('请选择要撤销的流水！');
        return;
      }
      showModal('请确认是否批量撤销核销？', '').then(async() => {
        const res = await batchCancelWriteOff(this.selectData);
        if (res.code === 200) {
          this.selectData = [];
          this.ids = '';
          this.$refs.chargeRecordTable.clearSelection();
          this.fetchData();
          ElMessage.success(res.message);
        }
      });
    },
    tableRowClassName({ row }) {
      return this.selectData.some(item => item.id === row.id) ? `table-selected` : '';
    },
    clearSelect() {
      showModal('是否清空已勾选的数据？', '').then(() => {
        this.selectData = [];
        this.ids = '';
        this.$refs.chargeRecordTable.clearSelection();
      });
    },
    openOrderDetail(data) {
      const orderId = data.orderDetailId || '';
      if (!orderId) {
        this.$message.warning('无法获取订单详情信息');
        return;
      }
      const routerData = {
        name: 'orderDetail',
        params: { orderId }
      };
      const url = this.$router.resolve(routerData);
      window.open(url.href, '_blank');
    },
    openFlowDetail(data) {
      const chargeOffId = data.flowDetailId || '';
      if (!chargeOffId) {
        this.$message.warning('无法获取流水详情信息');
        return;
      }
      const routerData = {
        name: 'chargeOffDetail',
        params: { chargeOffId }
      };
      const url = this.$router.resolve(routerData);
      window.open(url.href, '_blank');
    },
    async getStatisticsData(params, cancelToken) {
      try {
        this.statisticsList = [
          { data: 0, label: '含税金额', icon: icon_4 },
          { data: 0, label: '核销金额', icon: icon_35 },
          { data: 0, label: '待封账订单', icon: icon_6 }
        ];
        const { page, perPage } = params;
        if (page) delete params.page;
        if (perPage) delete params.perPage;
        const res = await getchargeStatistics(params, cancelToken);
        const { code, data = {}} = res;
        if (code === 200) {
          const { writeAmount, taxAmount, beSealedOrder } = data;
          this.statisticsList = [
            { data: taxAmount / 100, label: '含税金额', icon: icon_4 },
            { data: writeAmount / 100, label: '核销金额', icon: icon_35 },
            { data: beSealedOrder, label: '待封账订单', icon: icon_6 }
          ];
        }
      } catch (error) {
        console.log(error);
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.charge-report-wrap {
  .table-list {
    margin: 16px 16px 0 16px;
    background-color: #fff;
    padding: 20px 20px 55px 20px;
    overflow: hidden;
  }
}
.flex{
  display: flex;
  justify-content: end;
}
</style>
